package org.example.yiyu.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.yiyu.exception.CustomException;
import org.example.yiyu.mapper.DiaryMapper;
import org.example.yiyu.model.Diary;
import org.example.yiyu.model.DiaryQuery;
import org.example.yiyu.service.DiaryService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class DiaryServiceImpl implements DiaryService {


    private final DiaryMapper diaryMapper;

    @Override
    public Long addDiary(Diary diary) {
        //先创建日记,并返回主键id值
        diaryMapper.insertDiary(diary);
        //再用返回的id值与标签值创建关联
        for (Long tagId : diary.getTagIds()) {
            Map<String, Object> params = new HashMap<>();
            params.put("diaryId", diary.getId());
            params.put("tagId", tagId);
            diaryMapper.insertDiaryTag(params);
        }
        return diary.getId();
    }

    @Override
    public void removeDiary(Long id) {

        //异常处理
        if (getDiary(id)==null) {
            log.info("操作失败");
            throw new CustomException(404,"Diary with id " + id + " not found");
        }


        diaryMapper.deleteDiary(id);
    }

    @Override
    public void modifyDiary(Diary diary) {

        //异常处理
        if (getDiary(diary.getId())==null) {
            log.info("操作失败");
            throw new CustomException(404,"Diary with id " + diary.getId() + " not found");
        }

        diaryMapper.updateDiary(diary);
    }

    @Override
    public Diary getDiary(Long id) {

        //异常处理
        if (diaryMapper.getDiaryById(id)==null) {
            log.info("操作失败");
            throw new CustomException(404,"Diary with id " + id + " not found");
        }

        return diaryMapper.getDiaryById(id);
    }

    @Override
    public List<Diary> searchDiaries(DiaryQuery query) {

        //把页数换算成起始序号数
        int offset= (query.getPage()-1)* query.getLimit();
        query.setPage(offset);

        //异常处理
        if (diaryMapper.findDiaries(query).isEmpty()) {
            log.info("未找到日记");
            throw new CustomException(404,"未查询到适合范围内的日记");
        }

        return diaryMapper.findDiaries(query);

    }


}
